# coding=utf-8
"""
作者：董新强 
创建时间：2020-3-22
描述：能力管理
"""
from sqlalchemy import and_

from db_models.cat_abilities import CatAbilities
from db_models.cat_test import CatTest
from framework.db_session import DbSession
from framework.log_util import trycatch
from framework.msg import ok, failure
from services.service_base import ServiceBase


class AbilityManage(ServiceBase):
    def __init__(self, usr):
        super().__init__(usr)

    @trycatch(failure(msg='获取能力列表失败'))
    def get_ability_list(self):
        ls = []
        with DbSession.create() as db:
            query = db.query(CatAbilities.id, CatAbilities.name, CatTest.status) \
                .filter(CatAbilities.pid == 0) \
                .filter(CatAbilities.status == 1) \
                .outerjoin(CatTest, and_(CatTest.uid == self.uid, CatTest.aid == CatAbilities.id)) \
                .order_by(CatAbilities.name)
            for id, name, status in query:
                ls.append({'id': id, 'name': name, 'status': 0 if not status else 1})

        return ok(data=ls)

    @trycatch(failure(msg='获取能力失败'))
    def get_child_abilities(self, pid):
        ls = []
        with DbSession.create() as db:
            query = db.query(CatAbilities, CatTest.score).filter(CatAbilities.pid == pid).filter(CatAbilities.status == 1) \
                .outerjoin(CatTest, and_(CatTest.aid == CatAbilities.id, CatTest.status == 1)) \
                .order_by(CatAbilities.name)
            for v, score in query:
                ls.append({'id': v.id, 'name': v.name, 'score': score})

        return ok(data=ls)


if __name__ == '__main__':
    pass
